package com.xpqh.ksg.exception;

import com.xpqh.ksg.common.enums.result.BizExceptionEnum;
import com.xpqh.ksg.common.utils.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Map;

/**
 * 全局的的异常拦截器（拦截所有的控制器）（带有@RequestMapping注解的方法上都会拦截）
 * @author 36115
 */
@Slf4j
@RestControllerAdvice
public class BaseExceptionHandler {

    /**
     * 拦截业务异常
     */
    @ExceptionHandler(WebApiException.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Map<String, Object> notFount(WebApiException e) {
    	log.error("运行时异常", e);
        return ResultUtil.toMap(null, e.getCode(), e.getMessage());
    }

    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public Map<String, Object> notFount(RuntimeException e) {
        log.error("运行时异常", e);
        return ResultUtil.ERROR(BizExceptionEnum.SERVER_ERROR);
    }

    /**
     * 拦截controller层的参数校验异常的数据
     */
    @ExceptionHandler(value = {MethodArgumentNotValidException.class})
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Map<String, Object> notFount(MethodArgumentNotValidException e) {
        String errorMessage = e.getBindingResult().getAllErrors().get(0).getDefaultMessage();
        return ResultUtil.toMap(null, BizExceptionEnum.PATAMS_EMPTY.getCode(),errorMessage);
    }
}
